package models

import (
	"time"
	"gorm.io/gorm"
)

// Post 定义了动态的数据模型
type Post struct {
	ID        uint           `gorm:"primarykey" json:"id"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `gorm:"index" json:"deleted_at,omitempty"`
	UserID   uint   `json:"user_id"`
	User     User   `gorm:"foreignKey:UserID" json:"user"`
	Content  string `json:"content"`
	ImageURL string `json:"image_url,omitempty"`
	Likes    int    `gorm:"default:0" json:"likes"`
}

func CreatePost(post *Post) error {
	return GetDB().Create(post).Error
}

func GetPostsByUserID(userID string) []Post {
	var posts []Post
	GetDB().Where("user_id = ?", userID).Order("created_at DESC").Preload("User").Find(&posts)
	return posts
}

func GetAllPosts(orderBy string) []Post {
	var posts []Post
	query := GetDB().Preload("User")

	switch orderBy {
	case "hot":
		query = query.Order("likes DESC, created_at DESC")
	default:
		query = query.Order("created_at DESC")
	}

	query.Find(&posts)
	return posts
}

func LikePost(postID uint) error {
	return GetDB().Model(&Post{}).Where("id = ?", postID).Update("likes", gorm.Expr("likes + ?", 1)).Error
}

func GetRecentPosts(limit int) []Post {
	var posts []Post
	GetDB().Preload("User").Order("created_at DESC").Limit(limit).Find(&posts)
	return posts
}
